//
// Created by JYL on 2024-06-17.
//
#include "voltage_task.h"
#include "cmsis_os.h"
#include "bsp_adc.h"
#include "math.h"
#include "stdio.h"



static float calc_battery_percentage(float voltage);


ADC adc;

/**
  * @brief          电源采样和计算电源百分比
  * @param[in]      pvParameters: NULL
  * @retval         none
  */
void Voltage_Task(void *argument)
{
    /* USER CODE BEGIN Voltage_Task */
    osDelay(1000);
    //use inner 1.2v to calbrate
    init_vrefint_reciprocal();
    /* Infinite loop */
    for(;;)
    {
        adc.battery_voltage = get_battery_voltage() + VOLTAGE_DROP;
        adc.Resister = get_resister_voltage();
        adc.Temperature = get_temprate();
        adc.electricity_percentage = calc_battery_percentage(adc.battery_voltage/3);  //作为平均电池百分比
        osDelay(100);
    }
    /* USER CODE END Voltage_Task */
}


static float calc_battery_percentage(float voltage)
{
    float percentage;
#define p1 (-505.4)
#define p2 ( 7006)
#define p3  (-3.605e+04)
#define p4  (8.164e+04)
#define p5 (-6.868e+04)
/*
 * //    float voltage_2 = voltage * voltage;
//    float voltage_3 = voltage_2 * voltage;
//
//    if(voltage < 19.5f)percentage = 0.0f;
//    else if(voltage < 21.9f)
//    {
//        percentage = 0.005664f * voltage_3 - 0.3386f * voltage_2 + 6.765f * voltage - 45.17f;
//    }
//    else if(voltage < 25.5f)
//    {
//        percentage = 0.02269f * voltage_3 - 1.654f * voltage_2 + 40.34f * voltage - 328.4f;
//    }
//    else
//    {
//        percentage = 1.0f;
//    }
//    if(percentage < 0.0f)
//    {
//        percentage = 0.0f;
//    }
//    else if(percentage > 1.0f)
//    {
//        percentage = 1.0f;
//    }
 * */
//另一套公式//another formulas
/*
//    if(voltage < 19.5f)
//    {
//        percentage = 0.0f;
//    }
//    else if(voltage < 22.5f)
//    {
////        percentage = 0.05776f * (voltage - 22.5f) * (voltage_2 - 39.0f * voltage + 383.4f) + 0.5f;
//        percentage = 0.05021f * voltage_3 - 3.075f * voltage_2 + 62.77f * voltage - 427.02953125f;
//    }
//    else if(voltage < 25.5f)
//    {
////        percentage = 0.01822f * (voltage - 22.5f) * (voltage_2 - 52.05f * voltage + 637.0f) + 0.5f;
//        percentage = 0.0178f * voltage_3 - 1.292f * voltage_2 + 31.41f * voltage - 254.903125f;
//    }
//    else
//    {
//        percentage = 1.0f;
//    }
 * */
    //注意voltage的范围是(350~420)
    if(voltage > 4.11)percentage=100;
    else if(voltage < 3.50)percentage=0;
    else percentage = p1*powf(voltage,4)+ p2*powf(voltage,3)
                     + p3*powf(voltage,2)+ p4*powf(voltage,1)+ p5;
    return percentage;
}

